/*
 * JF Updater: Auto-updater for modified Android OS
 *
 * Copyright (c) 2009 Sergi Vélez
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

package jfupdater.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.List;

import jfupdater.ui.ApplyUploadActivity;
import jfupdater.ui.R;
import jfupdater.ui.UpdateProcessInfo;
import jfupdater.utils.HexDump;
import jfupdater.utils.Preferences;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;


public class UpdateService extends Service {
	
	public static UpdateService INSTANCE;
	
	private static final String TAG = "UpdateService";
	
	public static final String UPDATE_FILE_NAME = "update.zip";
	public static final String KEY_UPDATE_LIST = "updates";
	public static final String KEY_REQUEST = "request";
	public static final String KEY_UPDATE_INFO = "updateInfo";
	public static final String KEY_UPDATE_FILE= "updateFile";
	public static final String KEY_REQUESTED_BY_USER = "reqByUser";
	
	public static final int REQUEST_CHECK_FOR_UPDATES = 1;
	public static final int REQUEST_DOWNLOAD_UPDATE = 2;
	
	
	private Looper mServiceLooper;
	private ServiceHandler mServiceHandler;
	private IUpdateServer mUpdateServer;
	private NotificationManager mNM;
	private File mUpdateFile;
	private MessageDigest mDigest;
	
	private volatile boolean mDownloading;
	
	private final class ServiceHandler extends Handler {

		public ServiceHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
            Bundle arguments = (Bundle)msg.obj;
            
            int request = arguments.getInt(KEY_REQUEST); 
            switch(request) {
            	case REQUEST_CHECK_FOR_UPDATES:
					checkForUpdates(arguments.getBoolean(KEY_REQUESTED_BY_USER));
					break;
            	
            	case REQUEST_DOWNLOAD_UPDATE:
					downloadUpdate((UpdateInfo)arguments.getSerializable(KEY_UPDATE_INFO));
					break;
            	
            	default:
            		Log.e(TAG, "Unknown request ID:" + request);
            }

            Log.i("ServiceStartArguments", "Done with #" + msg.arg1);
            stopSelf(msg.arg1);
		}
	}
	

	@Override
	public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        
		HandlerThread thread = new HandlerThread(TAG);
        thread.start();
        
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
		mUpdateFile = new File(Environment.getExternalStorageDirectory(), UPDATE_FILE_NAME);
		mUpdateServer = UpdateServerFactory.getDefaultUpdateServer();
		try {
			mDigest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("MD5 not found");
		}
		
		INSTANCE = this;
		mDownloading = false;
	}

	@Override
	public void onStart(Intent intent, int startId) {
        Log.i(TAG, "Starting #" + startId + ": " + intent.getExtras());
        
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent.getExtras();
        mServiceHandler.sendMessage(msg);
        Log.d("ServiceStartArguments", "Sending: " + msg);
	}

	@Override
	public void onDestroy() {
		mServiceLooper.quit();
		INSTANCE = null;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	public boolean isDownloading() {
		return mDownloading;
	}

	private void downloadUpdate(UpdateInfo ui) {
		mDownloading = true;
		try {
			mUpdateServer.downloadUpdateFile(ui, mUpdateFile);
			mDownloading = false;
			checkMD5(ui, mUpdateFile);
		} catch (IOException ex) {
			mDownloading = false;
			Log.e(TAG, "IOEx while downloading an update", ex);
			Toast.makeText(this, R.string.exception_while_downloading, Toast.LENGTH_SHORT);
			return;
		}
		
		Resources res = getResources();
		Intent i = new Intent(this, ApplyUploadActivity.class)
							.putExtra(KEY_UPDATE_INFO, ui)
							.putExtra(KEY_UPDATE_FILE, mUpdateFile);

		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i,
											PendingIntent.FLAG_CANCEL_CURRENT);
		
		Notification notification = new Notification(android.R.drawable.stat_notify_sync,
											res.getString(R.string.not_update_downloaded_ticker),
											System.currentTimeMillis());
		String notificationBody = MessageFormat.format(res.getString(R.string.not_update_downloaded_ticker),
											ui.displayName, ui.displayVersion);
		notification.setLatestEventInfo(this, res.getString(R.string.not_update_downloaded_title), notificationBody, contentIntent);
		
		Preferences.getPreferences(this).setDownloadedUpdate(ui);
		
		mNM.notify(R.string.not_update_downloaded_title, notification);
	}

	private void checkMD5(UpdateInfo ui, File updateFile) throws IOException {
		MessageDigest digest = mDigest;
		byte[] buff = new byte[4 * 1024];
		FileInputStream fis = new FileInputStream(updateFile);
		int read;
		
		while( (read = fis.read(buff)) > 0 ) {
			digest.update(buff, 0, read);
		}
		
		String calculatedDigest = new String(HexDump.toCharArray(digest.digest()));
		
		Log.d(TAG, "Calculated digest: " + calculatedDigest);
		Log.d(TAG, "Provided digest: " + ui.displayName);
		
		if(!calculatedDigest.equalsIgnoreCase(ui.md5)) {
			throw new IOException("md5 checksum failed");
		}
	}

	private void checkForUpdates(boolean requestedByUser) {
		Resources res = getResources();
		if(requestedByUser) {
			Toast.makeText(this, res.getString(R.string.checking_for_updates), Toast.LENGTH_SHORT);
		}
		
		List<UpdateInfo> availableUpdates;
		try {
			Log.i(TAG, "Checking for updates...");
			availableUpdates = mUpdateServer.getAvailableUpdates();
		} catch (IOException ex) {
			Log.e(TAG, "IOEx while checking for updates", ex);
			if(requestedByUser)
				Toast.makeText(UpdateService.this, R.string.exception_while_updating, Toast.LENGTH_SHORT);
			return;
		} catch (RuntimeException ex) {
			Log.e(TAG, "RuntimeEx while checking for updates", ex);
			if(requestedByUser)
				Toast.makeText(UpdateService.this, R.string.exception_while_updating, Toast.LENGTH_SHORT);
			return;
		}
		
		int updateCount = availableUpdates.size();
		Log.i(TAG, updateCount + " update(s) found");
		
		if(updateCount > 0) {
			Intent i = new Intent(this, UpdateProcessInfo.class)
							.putExtra(KEY_UPDATE_LIST, (Serializable)availableUpdates);
							//.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i,
												PendingIntent.FLAG_ONE_SHOT);
			
			Notification notification = new Notification(android.R.drawable.stat_notify_sync,
												res.getString(R.string.not_new_updates_found_ticker),
												System.currentTimeMillis());
			
			String text = MessageFormat.format(res.getString(R.string.not_new_updates_found_body), updateCount);
			notification.setLatestEventInfo(this, res.getString(R.string.not_new_updates_found_title), text, contentIntent);
			
			Preferences.getPreferences(this).setUpdateList(availableUpdates);
			
			//Use a resourceId as an unique identifier
			mNM.notify(R.string.not_new_updates_found_title, notification);
		} else {
			Log.i(TAG, "No updates found");
			
			//If the user asked for the update, notify them about the result
			if(requestedByUser) {
				Toast.makeText(this, R.string.no_updates_found, Toast.LENGTH_SHORT);
			}
		}
	}

}
